
package com.geofencing.service;

import com.geofencing.model.Geofence;
import com.geofencing.model.GeofenceDTO;
import com.geofencing.repository.GeofenceRepository;
import org.locationtech.jts.geom.*;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GeofenceService {
    private final GeofenceRepository geofenceRepository;
    private final GeometryFactory geometryFactory = new GeometryFactory();

    @Autowired
    public GeofenceService(GeofenceRepository geofenceRepository) {
        this.geofenceRepository = geofenceRepository;
    }

    public Geofence saveGeofence(String name, String wktPolygon) throws ParseException {
        Geofence geofence = new Geofence();
        geofence.setName(name);
        geofence.setPolygon((Polygon) new WKTReader().read(wktPolygon));
        return geofenceRepository.save(geofence);
    }

    public List<GeofenceDTO> findGeofenceContainingPoint(double longitude, double latitude) {
        Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
        List<Geofence> geofences = geofenceRepository.findGeofenceContainingPoint(point);
        if (geofences.isEmpty() || geofences.size() == 0) {
            return Collections.EMPTY_LIST;
        }
        List<GeofenceDTO> geofenceDTOList = new ArrayList<>();
        geofences.forEach(geofence -> {
            GeofenceDTO geofenceDTO = new GeofenceDTO();
            BeanUtils.copyProperties(geofence, geofenceDTO);
            geofenceDTOList.add(geofenceDTO);
        });
        return geofenceDTOList;
    }
}
